# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

"""Vieport module"""
from __future__ import division, absolute_import
import weakref
from src import game
from src import vars
from src.consts import *

class ViewPort(object):
    """Viewport (currently only one viewport is supported)"""
    def __init__(self, w, h, x=0, y=0):
        self.w, self.h = w, h # in pixels
        self._x, self._y = x, y # in pixels
        self.dx, self.dy = x, y
        self.x_shift, self.y_shift, = 0, 0
        self.objects = [] # objects currently in the viewport
        self.rect = []
        print 'add viewport w h', self.w, self.h
    def _set_x(self, val):
        self.dx = self._x - val
        self._x = val % game.field.w_px
        self.update_scroll()
    x = property(lambda self: self._x, _set_x)
    def _set_y(self, val):
        self.dy = self._y - val
        self._y = val % game.field.h_px
        self.update_scroll()
    y = property(lambda self: self._y, _set_y)
    def _set_x_shift(self, val):
        self.x_shift = val
        self.x = -val
    def update_scroll(self):
        # reset
        self.x_shift = -self.x
        self.y_shift = -self.y
        
        print 'xw', self.x, self.w, game.field.w_px
        vis_rect = [self.x, self.y, self.x + self.w, self.y + self.h]

        if self.x + self.w > game.field.w_px:
            wrapped_x = (self.x + self.w) - game.field.w_px
            vis_rect[0] = wrapped_x
            vis_rect[2] = wrapped_x + self.w
        self.rect = vis_rect
        # finalize
        self.dx = 0
        self.dy = 0
        return game.ctl.dispatch_event('on_viewport_scroll', self.rect)
    def scroll(self, dir):
        """controller function"""
        if dir == DIR_N:
            game.vp.y += vars.tile_size
        elif dir == DIR_S:
            game.vp.y -= vars.tile_size
        elif dir == DIR_E:
            game.vp.x += vars.tile_size
        elif dir == DIR_W:
            game.vp.x -= vars.tile_size

